<template>
  <ContentWrap>
    <!-- 模板选择 -->
    <el-form
      class="-mb-15px"
      ref="queryFormRef"
      :inline="true"
      label-width="80px"
    >
      <!-- <el-form-item label="模版类型" prop="documentType">
        <el-select v-model="printData.documentType" class="!w-240px">
          <el-option
            v-for="dict in getDictOptions(DICT_TYPE.ERP_DOCUMENT)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="默认状态" prop="status">
        <el-select v-model="printData.status" class="!w-240px">
          <el-option
            v-for="dict in getDictOptions(DICT_TYPE.ERP_DEFAULT_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="模版名称" prop="name">
        <el-input
          v-model="printData.name"
          placeholder="请输入模版名称"
          clearable
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="放大比例">
        <el-input-number
          style="margin: 0 10px"
          v-model="scaleValue"
          :precision="2"
          :step="0.1"
          :min="scaleMin"
          :max="scaleMax"
          @change="changeScale"
        />
      </el-form-item>
      <el-form-item>
        <!-- 预览/打印 -->
        <el-button plain type="primary" @click="back"> 返回 </el-button>
        <el-button plain type="primary" @click="preView"> 预览 </el-button>
        <el-button plain type="success" @click="save"> 保存 </el-button>
        <el-button plain type="danger" @click="clearPaper"> 清空 </el-button>
        <!-- 保存/清空 -->
      </el-form-item>
    </el-form>
    <!-- 纸张设置 -->
    <!-- <el-button
          v-for="(value, index) in paperTypes"
          @click="setPaper(index, value)"
          :key="index"
        >
          {{ index }}
        </el-button> -->
  </ContentWrap>

  <ContentWrap>
    <el-row :gutter="10">
      <el-col :span="4">
        <el-card style="height: 100vh">
          <el-row>
            <el-col :span="24">
              <!-- 左边模板  根据providers配置而来 -->
              <div class="rect-printElement-types hiprintEpContainer"></div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
      <el-col :span="14">
        <el-card class="card-design">
          <!-- 中间设计部分 -->
          <div id="hiprint-printTemplate" class="hiprint-printTemplate"></div>
        </el-card>
      </el-col>
      <el-col :span="6" class="params_setting_container">
        <el-card>
          <el-row class="hinnn-layout-sider">
            <!-- 右侧样式部分 -->
            <div id="PrintElementOptionSetting"></div>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
  </ContentWrap>

  <!-- 预览 -->
  <printPreview ref="preViewRef" />
</template>

<script setup lang="ts">
// import { PrintDocumentApi, PrintDocumentVO } from '@/api/erp/printdocument'
import { ref, onMounted } from "vue";
import printPreview from "./preview.vue";
import { hiprint } from "vue-plugin-hiprint";
import providers from "./providers";
import { getItem } from "./providers";
import { getData, setData } from "./print-data";
import $ from "jquery";
// import { getDictOptions, DICT_TYPE } from '@/utils/dict'
// const message = useMessage() // 消息弹窗
// const { query } = useRoute()
// const { back } = useRouter()
let hiprintTemplate;

const paperPopVisible = ref(true);
// const mode = ref(0)
const modeList: any = ref([]);
const curPaper = ref({
  type: "other",
  width: 210,
  height: 296.6,
});
const paperTypes = ref({
  A4: {
    width: 210,
    height: 296.6,
  },
});
const scaleValue = ref(1);
const scaleMax = ref(5);
const scaleMin = ref(0.5);
const paperWidth = ref("210");
const paperHeight = ref("296.6");
const printData: any = ref({
  id: null,
  name: "",
  documentType: "1",
  status: "1",
});
// 2. 定义计算属性 curPaperType
// const curPaperType = computed(() => {
//   let type = 'other'
//   const types = paperTypes.value
//   const currentPaper = curPaper.value
//   if (
//     !currentPaper ||
//     typeof currentPaper.width === 'undefined' ||
//     typeof currentPaper.height === 'undefined'
//   ) {
//     console.warn('curPaper prop is not properly defined.')
//     return type // 返回默认值或进行其他错误处理
//   }

//   const { width, height } = currentPaper

//   for (const key in types) {
//     // 确保 types[key] 是一个有效的对象并且有 width 和 height 属性
//     if (
//       types.hasOwnProperty(key) &&
//       types[key] &&
//       typeof types[key].width !== 'undefined' &&
//       typeof types[key].height !== 'undefined'
//     ) {
//       const item = types[key]
//       if (item.width === width && item.height === height) {
//         type = key
//         break // 优化：找到匹配项后立即退出循环
//       }
//     }
//   }
//   return type
// })
const init = async () => {
  try {
    // const res = await PrintDocumentApi.queryDocumentFields('1')
    // getItem(res)
    modeList.value = providers.map((e) => {
      return { type: e.type, name: e.name, value: e.value };
    });
    console.log(
      "🚀 modeList.value=providers.map     modeList.value:",
      modeList.value
    );
    changeMode();
  } catch (error) {
    console.log("🚀 init error:", error);
  }
};
const changeMode = async () => {
  let provider = providers[0];
  let templates = {};
  hiprint.init({
    providers: [provider.f],
  });
  $(".hiprintEpContainer").empty();
  hiprint.PrintElementTypeManager.build(".hiprintEpContainer", provider.value);
  $("#hiprint-printTemplate").empty();
  // try {
  //   if (query.id !== null) {
  //     printData.value = await PrintDocumentApi.getPrintDocument(query.id)
  //     console.log('🚀 changeMode    printData.value:', printData.value)
  //     templates = JSON.parse(printData.value.template)
  //   }
  // } catch (error) {
  //   console.log('🚀 changeMode error:', error)
  // }
  hiprintTemplate = new hiprint.PrintTemplate({
    template: templates,
    settingContainer: "#PrintElementOptionSetting",
    paginationContainer: ".hiprint-printPagination",
  });
  hiprintTemplate.design("#hiprint-printTemplate");
  // 获取当前放大比例, 当zoom时传true 才会有
  scaleValue.value = hiprintTemplate.editingPanel.scale || 1;
  await otherPaper();
};
/**
 * 设置纸张大小
 * @param type [A3, A4, A5, B3, B4, B5, other]
 * @param value {width,height} mm
 */
const setPaper = (type, value) => {
  try {
    if (Object.keys(paperTypes.value).includes(type)) {
      curPaper.value = {
        type: type,
        width: value.width,
        height: value.height,
      };
      hiprintTemplate.setPaper(value.width, value.height);
    } else {
      curPaper.value = {
        type: "other",
        width: value.width,
        height: value.height,
      };
      hiprintTemplate.setPaper(value.width, value.height);
    }
  } catch (error) {
    // message.error(`操作失败11: ${error}`)
  }
};

const changeScale = (currentValue, oldValue) => {
  let big = false;
  currentValue <= oldValue ? (big = false) : (big = true);
  let newScaleValue = scaleValue.value;
  if (big) {
    newScaleValue += 0.1;
    if (newScaleValue > scaleMax.value) newScaleValue = 5;
  } else {
    newScaleValue -= 0.1;
    if (newScaleValue < scaleMin.value) newScaleValue = 0.5;
  }
  if (hiprintTemplate) {
    // scaleValue: 放大缩小值, false: 不保存(不传也一样), 如果传 true, 打印时也会放大
    hiprintTemplate.zoom(newScaleValue);
    scaleValue.value = newScaleValue;
  }
};

const clearPaper = async () => {
  try {
    // await message.confirm('是否确认清空模板信息?', '警告')
    hiprintTemplate.clear();
  } catch (error) {
    console.log("🚀 clearPaper error:", error);
  }
};

const otherPaper = () => {
  let value: any = {};
  value.width = paperWidth.value;
  value.height = paperHeight.value;
  paperPopVisible.value = false;
  setPaper("other", value);
};
const preViewRef = ref();
const preView = () => {
  let { width } = curPaper.value;
  console.log(preViewRef.value);
  console.log(hiprintTemplate, "uuii");
  preViewRef.value.show(hiprintTemplate, getData(), width);
};

const save = async () => {
  // try {
  //   if (query.id === null) {
  //     await PrintDocumentApi.createPrintDocument({
  //       name: printData.value.name,
  //       documentType: printData.value.documentType,
  //       template: JSON.stringify(hiprintTemplate.getJson()),
  //       status: printData.value.status
  //     })
  //   } else {
  //     await PrintDocumentApi.updatePrintDocument({
  //       id: printData.value.id,
  //       name: printData.value.name,
  //       documentType: printData.value.documentType,
  //       template: JSON.stringify(hiprintTemplate.getJson()),
  //       status: printData.value.status
  //     })
  //   }
  //   message.success('保存成功')
  // } catch (error) {
  //   console.log('🚀 save error:', error)
  // }
};

onMounted(async () => {
  await init();
});
</script>

<style lang="scss" scoped>
// build 拖拽
:deep(.hiprint-printElement-type) > li > ul > li > a {
  padding: 4px 4px;
  color: #1296db;
  line-height: 1;
  height: auto;
  text-overflow: ellipsis;
}

// 默认图片
// :deep(.hiprint-printElement-image-content) {
//   img {
//     content: url('~@/assets/logo.png');
//   }
// }

// 设计容器
.card-design {
  overflow: hidden;
  overflow-x: auto;
  overflow-y: auto;
}
</style>
